<template>
  <div class="mod-config">
    <el-button type="primary" @click="uploadPic()">添加说明</el-button>
    <el-dialog
      title="添加使用说明"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="文件版本名称："
          prop="instructionName"
          :rules="[{ required: true, message: '说明版本名称不能为空' }]"
        >
          <el-input
            type="name"
            placeholder="请输入内容"
            v-model="form.instructionName"
            style="width: 50%"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="使用说明文件："
          prop="instructionSrc"
          :rules="[{ required: true, message: '使用说明文件不能为空' }]"
        >
          <el-upload
            class="upload-demo"
            :limit="1"
            drag
            action="http://121.41.167.195:8000/api/oss/upload"
            :file-list="fileList"
            :on-success="uploadSuccess"
            :on-exceed="uploadExceed"
            :on-remove="handleUploadRemove"
            :before-remove="beforeVodRemove"
            :before-upload="beforeTextUpload"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="insertPcSystem()">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="currentPdf"
      :visible.sync="currentdialogFormVisible"
      width="800"
    >
      <iframe ref="pdfCotainer" :src="currentPdfUrl" width="100%"></iframe>
    </el-dialog>
    <el-table
      :data="dataList"
      stripe
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column prop="id" label="说明版本id" width="180">
      </el-table-column>
      <el-table-column prop="instructionName" label="文件名称" width="180">
      </el-table-column>
      <el-table-column prop="createtime" sortable label="创建时间">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="readPdf(scope.row)"
            >查看</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
export default {
  data() {
    return {
      currentPdf: "",
      currentPdfUrl: "",
      currentdialogFormVisible: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dialogVisible: false,
      dialogFormVisible: false,
      form: {
        instructionName: "",
        instructionSrc: "",
      },
      fileList: [],
    };
  },
  components: {},
  activated() {
    this.getDataList();
  },
  methods: {
    // 上传课本之前的钩子函数
    beforeTextUpload(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      if (fileType !== ".pdf") {
        this.$message.error("上传文件只能是pdf");
        return false;
      }
      return true;
    },
    //查看当前的pdf
    readPdf(row) {
      this.currentdialogFormVisible = true;

      //   var pdfCotainer = this.$refs.pdfCotainer;
      //   pdfCotainer.height = document.documentElement.clientHeight;
      setTimeout(() => {
        var pdfCotainer = this.$refs.pdfCotainer;
        pdfCotainer.height = document.documentElement.clientHeight;
        this.currentPdf = row.instructionName;
        this.currentPdfUrl = row.instructionSrc;
      });
    },
    // 删除之前，就是点击x的时候
    beforeVodRemove(file) {
      return this.$confirm(`确定移除该文件？`);
    },
    // 点击确定的时候进行彻底删除
    handleUploadRemove() {
      this.form.instructionSrc = "";
      this.fileList = [];
    },
    //文件上传超出数量限制
    uploadExceed() {
      this.$message({
        message: "只能上传一个文件!",
        type: "error",
      });
    },
    //文件上传成功
    uploadSuccess(response, file, fileList) {
      this.fileList = [];
      let fileObj = {};
      let filenamelist = response.url.toString().split("/");
      fileObj["name"] = filenamelist[filenamelist.length - 1];
      fileObj["url"] = response.url;
      this.fileList.push(fileObj);
      this.form.instructionSrc = response.url;
    },
    //上传按钮事件
    uploadPic() {
      this.dialogFormVisible = true;
    },
    //存硬笔系统记录
    insertPcSystem() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/sf/teacherInstruction/save"),
            method: "post",
            data: this.$http.adornParams({
              instructionName: this.form.instructionName,
              instructionSrc: this.form.instructionSrc,
            }),
          }).then(({ data }) => {
            this.form.instructionName = "";
            this.form.instructionSrc = "";
            this.fileList = [];
            this.dialogFormVisible = false;
            this.$message({
              message: "添加成功!",
              type: "success",
            });
            this.getDataList();
          });
        } else {
          this.$message.error("文件名称不能为空或文件未上传！");
        }
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.form.instructionName = "";
          this.form.instructionSrc = "";
          this.fileList = [];
          done();
        })
        .catch((_) => {});
    },
    // 获取说明文件分页数据
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sf/teacherInstruction/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.teacherInstructionPage.records;
          this.totalPage = data.teacherInstructionPage.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 删除
    deleteHandle(editionId) {
      this.$confirm(`确定对[说明文件id=${editionId}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/teacherInstruction/delete"),
            method: "post",
            data: this.$http.adornData([editionId], false),
          }).then(({ data }) => {
            console.log(data);
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>